package com.jhw.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jhw.domain.Product;
import com.jhw.domain.PurchaseApply;
import com.jhw.domain.Stock;
import com.jhw.domain.StockWarningLog;
import com.jhw.dto.StockDto;
import com.jhw.exception.GlobalCustomException;
import com.jhw.exception.GlobalErrorCode;
import com.jhw.feign.ProductService;
import com.jhw.feign.PurchaseApplyService;
import com.jhw.mapper.StockMapper;
import com.jhw.result.JSONResult;
import com.jhw.service.IStockLogService;
import com.jhw.service.IStockService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jhw.service.IStockWarningLogService;
import com.jhw.util.AssertUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jhw
 * @since 2022-09-29
 */
@Service
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements IStockService {

    @Autowired
    private ProductService productService;

    @Value("${stock.WarningThreshold}")
    private Integer WarningThreshold;

    @Autowired
    private IStockWarningLogService stockWarningLogService;

    @Autowired
    private PurchaseApplyService purchaseApplyService;

    @Override
    public void inboundAndOutbound(StockDto dto) {
        Stock stock = selectStock(dto.getProductId());
        // 约定好当状态为0时表示待审核，要入库
        if (dto.getStatus() == 0){
            // 如果stock为空，就new一个并将传进来的参数设置进去
            if (stock == null){
                stock = new Stock();
                stock.setProductId(dto.getProductId());
                stock.setCount(dto.getCount());
                // 通过feign调用get接口，根据ProductId查询到返回的JSONResult
                JSONResult jsonResult = productService.get(dto.getProductId());
                // 断言是否成功，不成功就就返回一个报错数据
                AssertUtil.isTrue(jsonResult.isSuccess(), GlobalErrorCode.ERROR);
                // 获取JSONResult中的data数据
                Object data = jsonResult.getData();
                // 如果为空就报个码儿
                AssertUtil.isNotNull(data, GlobalErrorCode.ERROR);
                // 将json数据转成字符串
                String jsonString = JSONObject.toJSONString(data);
                // 将字符串转成Product对象
                Product product = JSON.parseObject(jsonString, Product.class);
                // 设置值到product
                product.setProductName(stock.getProductName());
                product.setCreateTime(new Date());
                // 添加到stock表
                insert(stock);
            }else {
                stock.setCount(stock.getCount() + dto.getCount());
                updateById(stock);
            }
            // 出库
        }else {
            Integer count = stock.getCount();
                // 库存不足
            if (count < dto.getCount() || count < WarningThreshold){
                    StockWarningLog stockWarningLog = new StockWarningLog();
                    BeanUtils.copyProperties(stock, stockWarningLog);
                    stockWarningLog.setCreateTime(new Date());
                    stockWarningLog.setInfo(stock.getProductName() + "注意！！！，库存不足了");
                    stockWarningLogService.insert(stockWarningLog);
                    PurchaseApply purchaseApply = new PurchaseApply();
                    BeanUtils.copyProperties(stock, purchaseApply);
                    purchaseApply.setCreateTime(new Date());
                    purchaseApply.setCount(69);
                    purchaseApply.setStatus(0);
                    purchaseApplyService.saveOrUpdate(purchaseApply);
                    throw new GlobalCustomException("库存不足");
                // 库存充足
            }else {
                stock.setCount(count-dto.getCount());
                updateById(stock);
                PurchaseApply purchaseApply = new PurchaseApply();
                BeanUtils.copyProperties(stock, purchaseApply);
                purchaseApply.setCreateTime(new Date());
                purchaseApply.setStatus(0);
                purchaseApply.setCount(69);
                purchaseApplyService.saveOrUpdate(purchaseApply);
                throw new GlobalCustomException("出库失败");
            }
        }

    }

    @Override
    public List<Stock> lack() {
        Wrapper<Stock> wrapper = new EntityWrapper<>();
        wrapper.le("count", WarningThreshold);
        List<Stock> stocks = selectList(wrapper);
        return stocks;
    }


    private Stock selectStock(Long productId) {
        Wrapper<Stock> wrapper = new EntityWrapper<>();
        wrapper.eq("product_id", productId);
        return selectOne(wrapper);
    }
}
